package com.dj.product.k2faas.jpa.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by 丁建 on 2025/9/23 09:52
 *
 * @author 丁建
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@Accessors(chain = true)

public class QueryArg {
    public static final String ORDER_COLUMNS = "_orderBy";

    private Pageable page;

    private Map<String, Object> args = new HashMap<>();

    public static QueryArg create() {
        return new QueryArg();
    }

    public QueryArg with(String key, Object value) {
        args.put(key, value);
        return this;
    }

    public QueryArg with(Pageable pageable) {
        page = pageable;
        var sort = page.getSort();
        if (sort == Sort.unsorted()) {
            return this;
        }
        var orderByColumns = sort.get().map(order -> " %s %s".formatted(order.getProperty(), order.getDirection())).collect(Collectors.joining(", "));
        args.put("_orderBy", "order by %s ".formatted(orderByColumns));
        return this;
    }
}
